/*----------------------------------------------
| noka select v1.0 www.97521.com                 |
| rebin 2014-01-15                             |
|---------------------------------------------*/
var nselectmulti = Class.create({
    version: '1.0',
    initialize : function(cfg) {
    	this.cfg = cfg;					//配置信息
    	this.id=cfg.id; //id
    	this.name=cfg.name;//name
    	this.iwidth=cfg.width;//宽
    	this.value = cfg.value;
    	this.sdy = $(cfg.id+'_sDiv');
    	this.json = cfg.json;//初始值
    	this.height = cfg.height;//高度
    	this.sql = cfg.sql;
    	this.onchange = cfg.onchange;
    	this.value = cfg.value;
    	this.readonly = ('readonly'==cfg.readonly);
    	this.disabled = ('disabled'==cfg.disabled);
    	this.allownull = cfg.allownull;//为true表示可以为空
    	this.placeholder = cfg.placeholder;
    	this.hImg;
    	this.mImg;
    	this.selectwidth = cfg.selectwidth;
    	this.optionwidth = cfg.optionwidth;
    	this.findsql = cfg.findsql;//查找sql
    	this.nowHeight = cfg.height;//高度
    	this.findValue = '';//查找框的值
    	this.fjson = [];//查找数据
    	this.dataurl = (undefined == cfg.dataurl?cfg.rurl+'/nokatag/nselect'+this.id+'.select':cfg.dataurl);
    	this.findurl = (undefined == cfg.findurl?cfg.rurl+'/nokatag/nselect'+this.id+'.ajaxinput': cfg.findurl);
    },
    show : function(){
    	var self = this;
    	self.PreLoding();
    	self.initselect();
    	self.initFindInput();
    	self.initObjCht();
    	setTimeout(function(){
    		self.setValues(self.value);
    	}, 100);
    },
    //-------------------初始化下拉框-------------------
    initselect : function(){
    	var idx = 0;
        var html = [];
        var self = this;
        var bodyHtml=$(self.id+'_selectDiv');
        self.iwidth-=18;
        //------------配置初始化--------------------------
        html[idx++] = '<div id="'+self.id+'_sidiv" class="select-dropdownchecklist  nk_input_lineheight nk_input_sdDiv" style="width:'+self.iwidth+'px;float:left;">';
        html[idx++] = '<input id="'+self.id+'_sinput"  placeholder="'+self.placeholder+'" class="nk_input_lineheight nk_select_input_text" type="text" style="width:'+self.iwidth+'px;" readonly="readonly" '+(self.disabled?'disabled="disabled"':'')+' value="">';
        html[idx++] = '<input id="'+self.id+'" name="'+self.name+'" type="hidden" value="'+self.value+'">';
        html[idx++] = '</div>';
        if(!self.allownull){
        	html[idx++] = '<div style="float:left;color: red;"  class="nk_input_imgheight">*</div>';
           	html[idx++] = '<div style="float:left;"><img style="display:none;vertical-align:middle" class="nk_input_imgheight" id="'+self.id+'_img" src="'+self.cfg.rurl+'/nokatag/formcheck/images/exclamation.gif"></img></div>';
        }
        bodyHtml.innerHTML=html.join('');
        //-----------加载事件-----------------------------
        var obj=$(self.cfg.id+'_sidiv');
        var tre=$(self.cfg.id+'_sboddiv');
        self.selectEvent(obj, tre);
        self.ExEvents();
        //-----------初始化内容---------------------------
        self.selectBody(tre);
    },
    //---------内容初始化-----------------------
    selectBody : function(obj){
    	var self = this;
    	if(''!=self.json){
    		self.jsonList();
    	}else if(''!=self.sql){
    		self.AjaxList();
    	}
    },
    initFindInput : function(){
    	var self = this;
    	var idx = 0;
    	var html = [];
        var body=$(self.cfg.id+'_sboddiv');
        var Lwidth = self.iwidth+20;
        if(undefined!=self.findsql){
        	html[idx++] ='<div id="'+self.id+'_findinput">';
        	html[idx++] ='<div class="nk_input_lineheight nk_input_sdDiv" style="width:'+Lwidth+'px">';
        	html[idx++] ='<div style="float: left;"><input id="'+self.id+'_findInputtext" style="width:'+self.iwidth+'px" class="nk_input_lineheight nk_select_input_text" type="text"></div>';
        	html[idx++] ='<div style="float: right;"><input  style="width:0px;height:0px;border:1px solid #ffffff;margin-top:-20px"><div id="'+self.id+'_finedInputButton" class="selectbutton-dropdownchecklistx">&nbsp;</div></div>';
        	html[idx++] ='</div>';
        	html[idx++] ='<div style="clear: both;"></div>';
        	html[idx++] ='</div><div id="'+self.id+'_fselect_body" style="overflow:auto;height:40px;overflow-x:hidden;"></div>';
        	body.innerHTML=html.join('');
        }
        if(undefined!=self.findsql){
	    	$(self.id+'_finedInputButton').observe('click',function(a){
	         	self.FindAjaxList();
	        });
	    	$(self.id+'_findInputtext').observe('keydown',function(event){
	    		switch(event.keyCode){
			       case 38://上
			         self.selectItemKey(false);
			         break;
			       case 40://下
			    	   self.selectItemKey(true);
			         break;
			       case 13://回车键
			    	 $$('.select-list_hover').each(function(alink,index) {
			    		 if(alink.id.indexOf(self.id+'_')!=-1){
			    			 alink.click();
			    			 return;
			    		 }
		    		 });
			    	 break;
		        }
	    	});
	    	$(self.id+'_findInputtext').observe('keyup',function(event){
	    		if(self.findValue!=this.value){
	    			self.findValue = this.value;
	    			if(self.findValue.length<2){
	    				self.FindAjaxList();
	    			}else{
	    				self.findPageJson(self.findValue);
	    			}
	    		}
	    	});
    	}
    },
    //-------------页面查找-----------------------
    findPageJson : function(value){
    	var self = this;
    	var fjson = self.fjson;
    	var tjson = [];
    	var idx=0;
    	if(undefined!=fjson){
    		for(var i=0;i<fjson.length;i++){
    			if(fjson[i].text.indexOf(value)!=-1){
    				tjson[idx++] = fjson[i];
    			}
    		}
    	}
    	self.json = tjson;
    	self.jsonList();
    },
    //-------------选择选项-----------------------
    selectItemKey : function(down){//true 向下   false 向上
    	var self = this;
    	var selectid = self.id+'_'+(self.allownull?1:0);
    	$$('.select-list_hover').each(function(alink,index) {
    		if(alink.id.indexOf(self.id+'_')!=-1){
    			selectid = alink.id;
    			return;
    		}
		 });
    	var idx = selectid.substring(selectid.lastIndexOf('_')+1,selectid.length);
    	if(down){
    		idx++;
    	}else{
    		idx--;
    	}
    	var sitem = $(self.id+'_'+idx);
    	if(undefined!=sitem){
    		$$('.select-list_hover').each(function(alink,index) {
    			if(alink.id.indexOf(self.id+'_')!=-1){
    				alink.removeClassName('select-list_hover');
    			}
    		 });
    		sitem.addClassName('select-list_hover');
    		try{
    			$(self.id+'_fselect_body').scrollTop=sitem.positionedOffset().top-30;
    		}catch(e){}
    	}
    },
    //-------------json 值加载-------------------
    jsonList : function(){// [{id:sss,f},{value:dd}]
    	var self = this;
    	var json = self.json;
    	var idx = 0;
        var html = [];
        var body=$(self.cfg.id+'_sboddiv');
        var Lwidth = self.iwidth+20;
        var Lheight=0;
        var selectStyle = 'width:'+Lwidth+'px;';
        if(self.selectwidth != undefined){//固定宽度
        	selectStyle = 'float: left;margin-right:5px;padding-right:3px;padding-left:3px;margin-bottom: 3px;border:1px solid #AFAFAF';
        }
        if(self.selectwidth != undefined && self.optionwidth != undefined){
        	selectStyle+=';width:'+self.optionwidth;
        }
    	for(var i=0;i<json.length;i++){
    		html[idx++] = '<div id="'+self.id+'_'+i+'" class="select-list '+(i==0?'select-list_hover':'')+'" style="'+selectStyle+'" title="'+json[i].text+'" alt="'+json[i].text+'">';
    		html[idx++] = '<input  style="vertical-align:middle;width: 14px;height: 14px;" id="'+self.id+'_'+i+'_ch" type="checkbox"  value="'+json[i].value+'">';
    		html[idx++] = json[i].text;
    		html[idx++] = '<input type="hidden" value="'+json[i].value+'" id="'+self.id+'_'+i+'_value">';
    		html[idx++] = '<input type="hidden" value="'+json[i].text+'"  id="'+self.id+'_'+i+'_text">';
    		html[idx++] = '<input type="hidden" value="'+json[i].text+'"  id="'+self.id+'_'+json[i].value+'_vt">';
    		html[idx++] = '</div>';
    		Lheight+=20;
    	}
    	if(undefined!=self.findsql){
    		$(self.id+'_fselect_body').innerHTML=html.join('');
    	}else{
    		body.innerHTML=html.join('');
    	}
    	if(Lheight<=self.height){
    		body.setStyle({height:Lheight+'px'});
    		self.nowHeight=Lheight;
    	}else{
    		body.setStyle({height:self.height+'px'});
    		self.nowHeight=self.height;
    	}
    	body.setStyle({width:(Lwidth-1)+'px'});
    	if(self.selectwidth != undefined){//固定宽度
    		body.setStyle({width:self.selectwidth});
    	}
    	self.setHeigthFindBody();
    	self.setFindInputFous();
    	self.initValue();
    	self.ListEvent(json);
    },
    //------------------ajax方式加载值--------------
    AjaxList : function(){
    	var self = this;
    	var idx = 0;//
    	var parsv=[];
    	var v = $(self.id).value;
    	parsv[idx++]=(''==self.sql?'':'&sql='+self.sql);
    	if(v.trim().length>0){
    		var sv = v.trim().split(',');
    		for(var s=0;s<sv.length;s++){
    			parsv[idx++]='&v='+sv[s];
    		}
    	}
    	if(undefined!=self.findsql){
    		parsv[idx++]='&fsql='+self.findsql;
    	}
    	new Ajax.Request(self.dataurl, {
    		method:'post',
            parameters: parsv.join(''),
            onSuccess: function(response) {
            	var nodes = response.responseText.evalJSON();//json数据    [{value:'fddd',text:'fddf'},{value:'fddd',text:'fddf'}]
            	self.json = nodes;
            	self.jsonList();
            }
    	});
    },
   //-------------------查询方式加载----------------------------------------------------
    FindAjaxList : function(){
    	var self = this;
    	var idx = 0;//
    	var parsv=[];
    	var v = $(self.id).value;
    	var findValue = $(self.id+'_findInputtext').value;
    	if(findValue.trim().length>0){//有输入值
	    	parsv[idx++]=(''==self.findsql?'':'&sql='+self.findsql);
	    	if(v.trim().length>0){
	    		var sv = v.trim().split(',');
	    		for(var s=0;s<sv.length;s++){
	    			parsv[idx++]='&v='+sv[s];
	    		}
	    	}
	    	if(undefined!=self.findsql){
	    		parsv[idx++]='&fsql='+self.findsql;
	    	}
	    	parsv[idx++]=(findValue.trim().length<1?'':'&pare='+encodeURIComponent(findValue.trim()));//查询参数
	    	new Ajax.Request(self.findurl, {
	    		method:'post',
	            parameters: parsv.join(''),
	            onSuccess: function(response) {
	            	var nodes = response.responseText.evalJSON();//json数据    [{value:'fddd',text:'fddf'},{value:'fddd',text:'fddf'}]
	            	self.json = nodes;
	            	//self.clearShowValue();
	            	self.jsonList();
	            	self.fjson = nodes;
	            }
	    	});
    	}else{
    		self.AjaxList();
    	}
    },
   //--------初始化验证-----------------
    initObjCht : function(){
    	var self = this;
    	$(self.id).veri = function(){
    	    if(($(self.id).value.trim().length<1) && !self.allownull){//不能为空
    	    	$(self.id+'_img').show();
    	    	return false;
    	    }
    	    try{$(self.id+'_img').hide();}catch(e){}
    	    return true;
    	};
    },
    //-----------------选择时，值处理----------------------------
    checkValue : function(v,t,checked){
    	var self = this;
    	var cstr=(''==$(self.id).value?',':','+$(self.id).value+',');//1,2,13,3,32->,1,2,13,3,32,
    	var vstr=(''==$(self.id+'_sinput').value?',':','+$(self.id+'_sinput').value+',');//1,2,13,3,32->,1,2,13,3,32,
		if(checked){
			if(cstr.indexOf(','+v+',')==-1){
				cstr+=v+',';
			}
			if(vstr.indexOf(','+t+',')==-1){
				vstr+=t+',';
			}
		}else{
			var vc=','+v+',';
			var reg=new RegExp(vc);
			cstr=cstr.replace(reg, ',');
			
			var tc=','+t+',';
			var teg=new RegExp(tc);
			vstr=vstr.replace(teg, ',');
		}
		$(self.id).value=(','==cstr?'':cstr.substring(1,cstr.length-1));
		$(self.id+'_sinput').value=(','==vstr?'':vstr.substring(1,vstr.length-1));
		var sortValue = self.systemSort($(self.id).value);
		if(undefined!=sortValue){
			$(self.id).value=sortValue;
		}
    },
    //------------------列表单击事件----------------
    ListEvent : function(json,maxWidth){
    	var self = this;
    	var textObj = $(self.id+'_sinput');
        var valueObj =$(self.id);
    	for(var i=0;i<json.length;i++){
    		//----------行单击-----------------------------
    		$(self.id+'_'+i).observe('click',function(a){
    			$(this.id+'_ch').checked=!$(this.id+'_ch').checked;
    			self.CheckList(this.id,$(this.id+'_ch').checked);
            });
    		//--------选框单击----------------------------
    		$(self.id+'_'+i+'_ch').observe('click',function(event){
    			var e=(event)?event:window.event;
    			if (window.event) {
    			   e.cancelBubble=true;
    			} else {
    			   e.stopPropagation();
    			}
    			var id=this.id;
    			id = id.substring(0,id.length-3);
    			self.CheckList(id,this.checked);
            });
    		$(self.id+'_'+i).observe('mousemove',function(a){
    			this.setStyle({color:'#ffffff',backgroundColor:'#000080'});
            });
    		$(self.id+'_'+i).observe('mouseout',function(a){
    			this.setStyle({color:'#000000',backgroundColor:'#ffffff'});
            });
    	}
    },
    //-----------选中值----------------------------------
    CheckList : function(id,checked){
    	var self = this;
		var v=$(id+'_value').value;
		var t=$(id+'_text').value;
		var ns = [];
		var vn = v.split(',');
		for(var c=0;c<vn.lenth;c++){
			ns[ns.length]={value:vn[c],text:$(self.id+'_'+vn[c]+'_vt').value};
		}
		ns[ns.length] = {value:v,text:t};
		if(self.onchange(ns)){
			self.checkValue(v,t,checked);
		}
		try{$(self.id+'_img').hide();}catch(e){}
		$(self.id).veri();
		self.value = v;
		self.setFindInputFous();
    },
    //----------------外部事件---------------------
    ExEvents : function(){
    	var self = this;
    	var textObj = $(self.id+'_sinput');
        var valueObj =$(self.id);
        
    	//------------刷新sql数据------------------
    	$(self.id).Reload = function(){
    		self.AjaxList();
    		textObj.value='';
            valueObj.value='';
    	};
    	//------------设置值------------------
    	$(self.id).setValue = function(v){
    		self.setValues(v);
    	};
    	//----------设置json----------------------
    	$(self.id).setJson = function(json){
    		self.json = json;
    		self.jsonList();
    		textObj.value='';
            valueObj.value='';
    	};
    	//----------------------------------
    	$(self.id).setDisabled = function(a){
    		$(self.id+'_sinput').writeAttribute({disabled:a});
    		self.disabled=a;
    	};
    	$(self.id).setReadonly = function(a){
    		$(self.id+'_sinput').writeAttribute({readonly:a});
    		self.readonly=a;
    	};
    },
    setValues : function(v){
    	var self = this;
    	var textObj = $(self.id+'_sinput');
        var valueObj =$(self.id);
    	valueObj.value = v;
        var json = self.json;
        var vc=v.split(',');
        var tv=',';
        if(undefined!=self.findsql){
        	self.AjaxList();//重新加载选项
        }
        for(var c=0;c<json.length;c++){
     		$(self.id+'_'+c+'_ch').checked=false;
     	}
        for(var a=0;a<vc.length;a++){
	            for(var i=0;i<json.length;i++){
	            	if(json[i].value==vc[a]){
	            		tv+=json[i].text+',';
	            		$(self.id+'_'+i+'_ch').checked=true;
	            		break;
	            	}
	            }
        }
        textObj.value = (','==tv?'':tv.substring(1,tv.length-1));
        try{$(self.id+'_img').hide();}catch(e){}
    },
    //-----------初始化选择框值-----------------------------------
    initValue : function(){
    	var self = this;
    	var v = $(self.id).value;
    	var textObj = $(self.id+'_sinput');
    	var json = self.json;
    	var vc=v.split(',');
    	var tv=',';
    	for(var a=0;a<vc.length;a++){
            for(var i=0;i<json.length;i++){
            	if(json[i].value==vc[a]){
            		$(self.id+'_'+i+'_ch').checked=true;
            		tv+=json[i].text+',';
            		break;
            	}
            }
    	}
    	textObj.value = (','==tv?'':tv.substring(1,tv.length-1));
    },
   //----------------清空显示值和实际值----------------
    clearShowValue : function(){
    	var self = this;
    	$(self.id+'_sinput').value='';
        $(self.id).value='';
    },
    //--------------------重设查找区域高度-------------------------------------------------------
    setHeigthFindBody : function(){
    	var self = this;
    	if(undefined!=self.findsql){
    		try{
    			var findHeight = $(self.id+'_findinput').getHeight();//查找输入框的高度
    			var xheight = self.nowHeight + findHeight+2;
    			$(self.id+'_sboddiv').setStyle({height:xheight+'px'});
    			$(self.id+'_fselect_body').setStyle({height:self.nowHeight+'px'});
    		}catch(e){}
    	}
    },
    setFindInputFous : function(){
    	var self = this;
    	try{
			$(self.id+'_findInputtext').focus();
		}catch(e){}
    },
    //===================下拉框事件============================================================
    selectEvent : function(obj,tre){
    	var self = this;
        var miFlg = true;
    	obj.observe('click',function(a){
    		if(self.readonly || self.disabled){
    			return;
    		}
    		var atop = obj.positionedOffset().top+obj.offsetHeight;
    		var aleft = obj.positionedOffset().left;
        	tre.absolutize();
        	tre.style.top=atop;
        	tre.style.left=aleft;
        	tre.setStyle({left:aleft+'px',top:atop+'px'});
        	tre.show();
        	self.setHeigthFindBody();
        	self.setFindInputFous();
        	try{
        		if(undefined!=self.findsql){
        			$(self.id+'_findInputtext').value='';
        			self.findValue ='';
        			self.FindAjaxList();
        		}
        	}catch(e){}
        });
        obj.observe('mousemove',function(){
    		miFlg = true;
    		self.setSelectStyle(obj);
    	});
        
        obj.observe('mouseout',function(event){
        	miFlg = false;
        	var element = event.element();
        	setTimeout(function(){
                if (element.descendantOf(self.sdy) && !miFlg){
                	self.setNoSelectStyle(obj);
                	tre.hide();
                }
            }, 500);
        });
        
        tre.observe('mousemove',function(){
    		miFlg = true;
    		self.setSelectStyle(obj);
    	});
        tre.observe('mouseout',function(event){
        	miFlg = false;
        	var element = event.element();
        	setTimeout(function(){
                if (element.descendantOf(self.sdy) && !miFlg){
                	self.setNoSelectStyle(obj);
                	tre.hide();
                }
            }, 500);
        });
        document.observe('widget:noka_reinit',function(event){//失失焦点时验证其值
       	if(self.id.indexOf('_nkADinsert_')==-1){
    	    	var npfffs=event.memo.widgetNumber.clone();
    	    	for(var i=0;i<npfffs.length;i++){
    	    		var cfgid = Object.allclone(self.cfg);
    	    		var initem = npfffs[i];
	    			cfgid.id = initem.id;
	    			if(undefined!=initem.value){
	    				cfgid.value = initem.value;
	    			}
    	    		if(cfgid.id.indexOf('_'+self.id+'_')!=-1){
    	    			if(undefined !=cfgid.lower && cfgid.lower.trim().length>0){
    	    				var reg=new RegExp('_'+self.id+'_','g');
    	    				var ssf = cfgid.id.split(reg);
    	    				cfgid.lower = ssf[0]+'_'+cfgid.lower+'_'+ssf[1];
    	    			}
    	    			(new nselectmulti(cfgid)).show();
    	    			try{
	    					var idx = cfgid.id.substring(cfgid.id.lastIndexOf('_')+1,cfgid.id.length);
	    					$(cfgid.id).name=$(cfgid.id).name.replace(/\[0\]/g,'['+idx+']');
	    				}catch(e){}
    	    		}
    	    	}
       }
      });
    },
    //------------排序-----------------------
    systemSort : function(values){
    	var vls = values.split(',');
    	return vls.sort(function(a, b) {
    		try{
    			return parseInt(a)-parseInt(b);
    		}catch(e){}
    	});
    },
   //----------选种状态-----------------------
    setSelectStyle : function(obj){
    	var self = this;
    	obj.setStyle({borderColor:'#5794bf',backgroundImage:'url('+self.hImg.src+')'});
    },
    //-----------未选种状态-------------------
    setNoSelectStyle : function(obj){
    	var self = this;
    	obj.setStyle({borderColor:'#AFAFAF',backgroundImage:'url('+self.mImg.src+')'});
    },
    //-----------预加载图片-------------------
    PreLoding : function(){
    	var self = this;
    	self.hImg = new Image(); 
    	self.mImg = new Image();
    	self.hImg.src=self.cfg.rurl+'/nokatag/org/noka/select/dropdown_hover.png';
    	self.mImg.src=self.cfg.rurl+'/nokatag/org/noka/select/dropdown.png';
    	NBackgroundImageCache();
    }
});